const express = require('express');
const router = express.Router();
const { Course, User, Chapter, Category } = require('../models');
const { successResponse, failureResponse } = require('../utils/responses')
const { NotFoundError } = require('../utils/errors')

router.get('/', async (req, res) => {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1
    const pageSize = Math.abs(Number(query.pageSize)) || 10
    const offset = (currentPage - 1) * pageSize;
    if (!query.categoryId) {
      throw new Error('分类ID不能为空');
    }

    const condition = {
      attributes: { exclude: ['CategoryId', 'UserId', 'content'] },
      where: { categoryId: query.categoryId },
      order: [['id', 'DESC']],
      limit: pageSize,
      offset: offset,
    };

    const { count, rows } = await Course.findAndCountAll(condition);
    successResponse(res, '成功查询分类', {
      courses: rows,
      pagination: {
        currentPage,
        pageSize,
        total: count,
      }
    });
  } catch (error) {
    failureResponse(res, error);
  }
});

router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params
    const condition = {
      attributes: { exclude: ['UserId', 'CategoryId'] },
    }
    const course = await Course.findByPk(id, condition);
    if (!course) throw new NotFoundError(`ID: ${id} 的课程不存在`);
    const category = await course.getGategory({
      attributes: ['id', 'name'],
    });
    const user = await course.getUser({
      attributes: ['id', 'username', 'nickname', 'avatar', 'company'],
    });
    const chapters = await course.getChpaters({
      attributes: ['id', 'titel', 'rank', 'createdAt'],
      order: [['rank', 'ASC'], ['id', 'DESC']]
    });
    successResponse(res, '成功查询课程详情', {
      course,
      category,
      user,
      chapters,
    });
  } catch (error) {
    failureResponse(res, error);
  }
});

module.exports = router;